package com.ruoyi.web.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.iot.domain.IotDataTermite;
import com.ruoyi.iot.domain.IotDataWaterQuality;
import com.ruoyi.web.common.util.format.WaterQualityUtil;
import org.apache.commons.codec.DecoderException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class WaterQualityHTTPUtil {

    //登录
    private static final String API_URL_LOGIN = "http://182.40.192.211:8081/api/auth/login";
    //氨氮
    private static final String API_URL_Amnitro = "http://182.40.192.211:8081/api/plugins/telemetry/DEVICE/587d0f20-c657-11ef-8ea6-9fc3cff1c93b/values/timeseries?keys=Amnitro";
    //总磷
    private static final String API_URL_TP = "http://182.40.192.211:8081/api/plugins/telemetry/DEVICE/68694ac0-c657-11ef-8ea6-9fc3cff1c93b/values/timeseries?keys=TP";
    //其它
    private static final String API_URL = "http://182.40.192.211:8081/api/plugins/telemetry/DEVICE/6f7574a0-c0ef-11ef-b453-1f5ba22b638c/values/timeseries?keys=turbidity,waterT,COD,waterPH,waterEC,dissolvedoxygen,chlorophyll,bgalgae";

    private static final String TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTY5OTM2MjQ1QHFxLmNvbSIsInVzZXJJZCI6IjZlNDgxMmQwLWQ2ZDUtMTFlZi04ZGU3LWNmMmI2YTViZDRmMyIsInNjb3BlcyI6WyJDVVNUT01FUl9VU0VSIl0sInNlc3Npb25JZCI6IjA3NjY2N2ExLTRhZTctNDBkZi05MGYxLTU2M2Q5MDkyM2FmZCIsImlzcyI6InRoaW5nc2JvYXJkLmlvIiwiaWF0IjoxNzM3MzYyMjg2LCJleHAiOjE3MzMzNzEyODYsImVuYWJsZWQiOnRydWUsImlzUHVibGljIjpmYWxzZSwidGVuYW50SWQiOiJmYWZiYTY5MC0zNDU3LTExZWYtOTE5Zi0xMTBmNGQyZDczODgiLCJjdXN0b21lcklkIjoiMjViOWIzYzAtZDZkNS0xMWVmLThkZTctY2YyYjZhNWJkNGYzIn0.ATMxbNGwfEZCounLbsREiKAC3BP1jekiOhGxhGoKCZBNg02-qsvQO_thnNeMdt5ebPv8y_QYhzMWKfXOR-Lm3g"; // 替换为实际的 token
// //登录
//    private static final String API_URL_LOGIN = "http://182.40.193.119:8081/api/auth/login";
//    //氨氮
//    private static final String API_URL_Amnitro = "http://182.40.193.119:8081/api/plugins/telemetry/DEVICE/587d0f20-c657-11ef-8ea6-9fc3cff1c93b/values/timeseries?keys=Amnitro";
//    //总磷
//    private static final String API_URL_TP = "http://182.40.193.119:8081/api/plugins/telemetry/DEVICE/68694ac0-c657-11ef-8ea6-9fc3cff1c93b/values/timeseries?keys=TP";
//    //其它
//    private static final String API_URL = "http://182.40.193.119:8081/api/plugins/telemetry/DEVICE/6f7574a0-c0ef-11ef-b453-1f5ba22b638c/values/timeseries?keys=turbidity,waterT,COD,waterPH,waterEC,dissolvedoxygen,chlorophyll,bgalgae";
//
//    private static final String TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTY5OTM2MjQ1QHFxLmNvbSIsInVzZXJJZCI6IjZlNDgxMmQwLWQ2ZDUtMTFlZi04ZGU3LWNmMmI2YTViZDRmMyIsInNjb3BlcyI6WyJDVVNUT01FUl9VU0VSIl0sInNlc3Npb25JZCI6IjA3NjY2N2ExLTRhZTctNDBkZi05MGYxLTU2M2Q5MDkyM2FmZCIsImlzcyI6InRoaW5nc2JvYXJkLmlvIiwiaWF0IjoxNzM3MzYyMjg2LCJleHAiOjE3MzMzNzEyODYsImVuYWJsZWQiOnRydWUsImlzUHVibGljIjpmYWxzZSwidGVuYW50SWQiOiJmYWZiYTY5MC0zNDU3LTExZWYtOTE5Zi0xMTBmNGQyZDczODgiLCJjdXN0b21lcklkIjoiMjViOWIzYzAtZDZkNS0xMWVmLThkZTctY2YyYjZhNWJkNGYzIn0.ATMxbNGwfEZCounLbsREiKAC3BP1jekiOhGxhGoKCZBNg02-qsvQO_thnNeMdt5ebPv8y_QYhzMWKfXOR-Lm3g"; // 替换为实际的 token

    private static final List<String> sensorIds = Arrays.asList(
        "PH-A001",
        "WDCGQ-A001",
        "RYFXY-A001",
        "DDDFXY-A001",
        "ZDFXY-A001",
        "NHFXY-A001",
        "YLSAFXY-A001",
        "ZMDFXY-A001",
        "CODFXY-A001",
        "ZLFXY-A001"
    );
    public static JSONObject login(String url, String username, String password) {
        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createPost(url);

        // 设置请求体参数为 JSON 格式
        JSONObject jsonParam = JSONUtil.createObj()
            .put("username", username)
            .put("password", password);

        request.body(jsonParam.toString(), "application/json");

        // 发送请求并获取响应
        String response = request.execute().body();

        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);
//        System.out.println(jsonObject);

        return jsonObject;
    }

    public static JSONObject fetchDataWithToken(String url,String token) {
        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createGet(url);

        // 添加请求头，包含 token
        request.header("Authorization", "Bearer " + token);

        // 发送请求并获取响应
        String response = request.execute().body();

        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);

        return jsonObject;
    }

    public static List<IotDataWaterQuality> convertUnits() {
        List<IotDataWaterQuality> resultList = new ArrayList<>();
        IotDataWaterQuality one = new IotDataWaterQuality();
        String token = login(API_URL_LOGIN, "1569936245@qq.com", "123456").get("token").toString();

        JSONObject amnitro = fetchDataWithToken(API_URL_Amnitro,token);
        // 氨氮 N(6,2) 两位小数
        one.setValueNH4N(formatDouble(getValueFromJSONObject(amnitro, "Amnitro"),2));

        // 总磷 TP N(5,3) 两位小数
        JSONObject tp = fetchDataWithToken(API_URL_TP,token);
        one.setValueTP(formatDouble(getValueFromJSONObject(tp, "TP"),3));

        //其它
        JSONObject other = fetchDataWithToken(API_URL,token);
        //PH N(4,2)
        one.setValuePH(formatDouble(getValueFromJSONObject(other, "waterPH"),2));
        //温度 N(3,1)
        one.setValueC(formatDouble(getValueFromJSONObject(other, "waterT"),2));
        //电导率 N(5) 且转换单位 us/cm --> ms/m   除以10
//        one.setValueCOND(formatDouble(getValueFromJSONObject(other, "waterEC"),0,10.0));
        one.setValueCOND(formatDouble(getValueFromJSONObject(other, "waterEC"),0));
        //浊度 N(3)
        one.setValueTURB(formatDouble(getValueFromJSONObject(other, "turbidity"),0));
        //COD N(6,2)
//        one.setValueCOD(formatDouble(getValueFromJSONObject(other, "COD"),2));
        one.setValueCOD(formatDouble(divideByRange(getValueFromJSONObject(other, "COD")),2));
        //溶氧 N(4,1)
        one.setValueDO(formatDouble(getValueFromJSONObject(other, "dissolvedoxygen"),1));
        //叶绿素 N(4,2)  ug/L  --> mg/L   除以1000
//        one.setValueCHLA(formatDouble(getValueFromJSONObject(other, "chlorophyll"),2,1000.0));
        one.setValueCHLA(formatDouble(getValueFromJSONObject(other, "chlorophyll"),2,10.0));
        //蓝绿藻密度 N(8,2)
        one.setValueZMD(formatDouble(getValueFromJSONObject(other, "bgalgae"),2,400.0));

        one.setReportTime(new Date());

        sensorIds.forEach(sensorId -> {
            IotDataWaterQuality copy = new IotDataWaterQuality();
            BeanUtil.copyProperties(one, copy);
            copy.setSensorId(sensorId);
            copy.setRemoteId("b070209243");
            resultList.add(copy);
        });
        return resultList;
    }

    public static List<IotDataWaterQuality> jsonToList(JSONObject json){
        List<IotDataWaterQuality> resultList = new ArrayList<>();
        IotDataWaterQuality one = new IotDataWaterQuality();
        // 氨氮 N(6,2) 两位小数
        one.setValueNH4N(formatDouble(getValueFromJSONObject1(json, "Amnitro"),2));

        // 总磷 TP N(5,3) 两位小数
        one.setValueTP(formatDouble(getValueFromJSONObject1(json, "TP"),3));

        //其它
        //PH N(4,2)
        one.setValuePH(formatDouble(getValueFromJSONObject1(json, "waterPH"),2));
        //温度 N(3,1)
        one.setValueC(formatDouble(getValueFromJSONObject1(json, "waterT"),2));
        //电导率 N(5) 且转换单位 us/cm --> ms/m   除以10
//        one.setValueCOND(formatDouble(getValueFromJSONObject1(other, "waterEC"),0,10.0));
        one.setValueCOND(formatDouble(getValueFromJSONObject1(json, "waterEC"),0));
        //浊度 N(3)
        one.setValueTURB(formatDouble(getValueFromJSONObject1(json, "turbidity"),0));
        //COD N(6,2)
//        one.setValueCOD(formatDouble(getValueFromJSONObject1(other, "COD"),2));
        one.setValueCOD(formatDouble(divideByRange(getValueFromJSONObject1(json, "COD")),2));
        //溶氧 N(4,1)
        one.setValueDO(formatDouble(getValueFromJSONObject1(json, "dissolvedoxygen"),1));
        //叶绿素 N(4,2)  ug/L  --> mg/L   除以1000
//        one.setValueCHLA(formatDouble(getValueFromJSONObject1(other, "chlorophyll"),2,1000.0));
        one.setValueCHLA(formatDouble(getValueFromJSONObject1(json, "chlorophyll"),2,10.0));
        //蓝绿藻密度 N(8,2)
        one.setValueZMD(formatDouble(getValueFromJSONObject1(json, "bgalgae"),2,400.0));

        one.setReportTime(new Date());

        sensorIds.forEach(sensorId -> {
            IotDataWaterQuality copy = new IotDataWaterQuality();
            BeanUtil.copyProperties(one, copy);
            copy.setSensorId(sensorId);
            copy.setRemoteId("b070209243");
            resultList.add(copy);
        });
        return resultList;
    }

    /**
     * 将 String 类型的 double 值保留指定的小数位数
     *
     * @param doubleStr 需要格式化的 double 值的字符串表示
     * @param scale     需要保留的小数位数
     * @return 格式化后的字符串
     * @throws NumberFormatException 如果输入的字符串不能被解析为 double 类型
     */
    public static String formatDouble(String doubleStr, int scale) {
        if (doubleStr == null || doubleStr.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }
        BigDecimal bd = new BigDecimal(doubleStr);
        bd = bd.setScale(scale, RoundingMode.HALF_UP);
        return bd.toPlainString();
    }

    /**
     * 格式化 double 字符串，并根据指定的比率进行单位转换
     *
     * @param doubleStr 输入的 double 字符串
     * @param scale     小数点后的位数
     * @param ratio     转换单位的比率
     * @return 格式化后的字符串
     * @throws IllegalArgumentException 如果输入字符串为 null 或空，或者比率小于等于 0
     */
    public static String formatDouble(String doubleStr, int scale, double ratio) {
        if (doubleStr == null || doubleStr.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }
        if (ratio <= 0) {
            throw new IllegalArgumentException("Ratio must be greater than 0");
        }

        BigDecimal bd = new BigDecimal(doubleStr);
        bd = bd.divide(new BigDecimal(ratio), scale, RoundingMode.HALF_UP);
        return bd.toPlainString();
    }

    /**
     * 从 JSONObject 中获取指定键的 value 字段
     *
     * @param jsonObject 目标 JSONObject 对象
     * @param key        要获取值的键
     * @return 指定键的 value 字段值，如果键不存在或值为 null，则返回 null
     */
    public static String getValueFromJSONObject1(JSONObject jsonObject, String key) {
        if (jsonObject == null || key == null) {
            return null;
        }

        // 获取指定键的值
        Object value = jsonObject.get(key);
        if (value == null ) {
            return null;
        }


        return value.toString();
    }

    /**
     * 从 JSONObject 中获取指定键的 value 字段
     *
     * @param jsonObject 目标 JSONObject 对象
     * @param key        要获取值的键
     * @return 指定键的 value 字段值，如果键不存在或值为 null，则返回 null
     */
    public static String getValueFromJSONObject(JSONObject jsonObject, String key) {
        if (jsonObject == null || key == null) {
            return null;
        }

        // 获取指定键的值
        Object value = jsonObject.get(key);
        if (value == null || !(value instanceof JSONArray)) {
            return null;
        }

        JSONArray jsonArray = (JSONArray) value;
        if (jsonArray.size() == 0) {
            return null;
        }

        // 获取数组中的第一个元素
        Object firstElement = jsonArray.get(0);
        if (firstElement == null || !(firstElement instanceof JSONObject)) {
            return null;
        }

        JSONObject firstObject = (JSONObject) firstElement;
        return firstObject.get("value").toString();
    }

    /**
     * 根据数值范围进行分段除法运算
     *
     * @param valueStr 输入数值字符串
     * @return 分段处理后的结果字符串
     */
    public static String divideByRange(String valueStr) {
        // 空值处理
        if (valueStr == null || valueStr.isEmpty()) {
            return "0.0"; // 默认返回 "0.0" 或者根据业务需求调整
        }

        double value;
        try {
            value = Double.parseDouble(valueStr);
        } catch (NumberFormatException e) {
            // 记录异常日志
            return "0.0"; // 默认返回 "0.0" 或者根据业务需求调整
        }

        double result;
        if (value <= 90) {
            result = value / 6;
        } else if (value <= 600) {
            result = value / 40;
        } else {
            result = value / 300;
        }

        // 使用格式化保留两位小数
        return String.format("%.2f", result);
    }

    public static Map<String, Object> convertParams(IotDataWaterQuality dataWaterQuality){

        Map<String, Object> map = new HashMap<>();

        Map<String, String> tags = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        //获取水质设备的遥测终端编号 默认取PH值编号
        tags.put("device_id", dataWaterQuality.getSensorId());
        tags.put("remote_id", dataWaterQuality.getRemoteId());

        fields.put("valuePH", dataWaterQuality.getValuePH());
        fields.put("valueDO", dataWaterQuality.getValueDO());
        fields.put("valueCOND", dataWaterQuality.getValueCOND());
        fields.put("valueTURB", dataWaterQuality.getValueTURB());

        fields.put("valueNH4N",dataWaterQuality.getValueNH4N());
        fields.put("valueTP", dataWaterQuality.getValueTP());

        fields.put("valueCHLA", dataWaterQuality.getValueCHLA());
        fields.put("valueC", dataWaterQuality.getValueC());
        fields.put("valueZMD", dataWaterQuality.getValueZMD());
        fields.put("valueCOD", dataWaterQuality.getValueCOD());
        fields.put("report_time", dataWaterQuality.getReportTime());

        map.put("fields", fields);
        map.put("tags", tags);

        return map;
    }

    public static  Map<String, Object> convertInfluxdbParams(IotDataWaterQuality dataWaterQuality){
        Map<String, Object> map = new HashMap<>();

        Map<String, String> tags = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        //获取水质设备的遥测终端编号 默认取PH值编号
        tags.put("deviceId", dataWaterQuality.getSensorId());
        tags.put("remoteId", dataWaterQuality.getRemoteId());

        fields.put("valuePH", dataWaterQuality.getValuePH());
        fields.put("valueDO", dataWaterQuality.getValueDO());
        fields.put("valueCOND", dataWaterQuality.getValueCOND());
        fields.put("valueTURB", dataWaterQuality.getValueTURB());

        fields.put("valueNH4N",dataWaterQuality.getValueNH4N());
        fields.put("valueTP", dataWaterQuality.getValueTP());

        fields.put("valueCHLA", dataWaterQuality.getValueCHLA());
        fields.put("valueC", dataWaterQuality.getValueC());
        fields.put("valueZMD", dataWaterQuality.getValueZMD());
        fields.put("valueCOD", dataWaterQuality.getValueCOD());
        fields.put("reportTime", dataWaterQuality.getReportTime().getTime());

        map.put("fields", fields);
        map.put("tags", tags);

        return map;
    }
    public static void main(String[] args) throws DecoderException {
//        fetchDataWithToken(API_URL_Amnitro);
//        System.out.println(formatDouble("2.1362",2));
        List<IotDataWaterQuality> waterQuality = convertUnits();
        System.out.println(waterQuality);
        waterQuality.forEach(one -> {
            String s = null;
            try {
                s = WaterQualityUtil.convertToHydrologicalProtocol(one);
            } catch (DecoderException e) {
                throw new RuntimeException(e);
            }
            System.out.println(s);
        });

//        login(API_URL_LOGIN, "1569936245@qq.com", "123456");
    }
}
